'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Users, Search, Filter, Edit, Trash2, UserPlus, Shield, Activity } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'


interface User {
  id: string
  username: string
  email: string
  school: string
  grade: number
  role: 'student' | 'admin'
  isActive: boolean
  lastLogin: string
  createdAt: string
  totalSessions: number
  averageAccuracy: number
}

export default function UsersManagePage() {
  const [users, setUsers] = useState<User[]>([])
  const [filteredUsers, setFilteredUsers] = useState<User[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedRole, setSelectedRole] = useState<string>('')
  const [selectedGrade, setSelectedGrade] = useState<string>('')
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  // 模拟用户数据
  const mockUsers: User[] = [
    {
      id: 'user-1',
      username: 'demo_student',
      email: 'student@demo.com',
      school: '演示小学',
      grade: 5,
      role: 'student',
      isActive: true,
      lastLogin: '2025-09-24T10:30:00Z',
      createdAt: '2025-09-15T09:00:00Z',
      totalSessions: 25,
      averageAccuracy: 85.2
    },
    {
      id: 'user-2',
      username: 'admin',
      email: 'admin@mathacademy.com',
      school: '系统管理',
      grade: 0,
      role: 'admin',
      isActive: true,
      lastLogin: '2025-09-24T11:15:00Z',
      createdAt: '2025-09-01T00:00:00Z',
      totalSessions: 0,
      averageAccuracy: 0
    },
    {
      id: 'user-3',
      username: 'zhangsan',
      email: 'zhangsan@example.com',
      school: '实验小学',
      grade: 4,
      role: 'student',
      isActive: true,
      lastLogin: '2025-09-23T16:45:00Z',
      createdAt: '2025-09-10T14:20:00Z',
      totalSessions: 18,
      averageAccuracy: 78.5
    },
    {
      id: 'user-4',
      username: 'lisi',
      email: 'lisi@example.com',
      school: '希望中学',
      grade: 7,
      role: 'student',
      isActive: false,
      lastLogin: '2025-09-20T09:30:00Z',
      createdAt: '2025-09-08T11:10:00Z',
      totalSessions: 12,
      averageAccuracy: 72.3
    }
  ]

  useEffect(() => {
    loadUsers()
  }, [])

  useEffect(() => {
    filterUsers()
  }, [users, searchQuery, selectedRole, selectedGrade])

  const loadUsers = async () => {
    try {
      setIsLoading(true)
      setError('')

      // 从API加载真实数据
      const response = await fetch('/api/admin/users', {
        credentials: 'include'
      })

      if (!response.ok) {
        throw new Error('加载用户失败')
      }

      const result = await response.json()

      if (result.success && result.data) {
        const formattedUsers = result.data.map((user: any) => ({
          id: user.id.toString(),
          username: user.username,
          email: user.email || '',
          school: user.school || '',
          grade: user.grade || 0,
          role: user.role || 'student',
          isActive: user.isActive !== false,
          lastLogin: user.lastLoginAt || user.createdAt,
          createdAt: user.createdAt,
          totalSessions: user.totalSessions || 0,
          averageAccuracy: user.averageAccuracy || 0
        }))

        setUsers(formattedUsers)
      } else {
        setError(result.error || '加载用户失败')
      }
    } catch (err) {
      console.error('加载用户错误:', err)
      setError('加载用户时发生错误')
    } finally {
      setIsLoading(false)
    }
  }

  const filterUsers = () => {
    let filtered = users

    // 搜索过滤
    if (searchQuery) {
      filtered = filtered.filter(user => 
        user.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
        user.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
        user.school.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }

    // 角色过滤
    if (selectedRole) {
      filtered = filtered.filter(user => user.role === selectedRole)
    }

    // 年级过滤
    if (selectedGrade) {
      filtered = filtered.filter(user => user.grade.toString() === selectedGrade)
    }

    setFilteredUsers(filtered)
  }

  const toggleUserStatus = async (userId: string) => {
    try {
      // 更新本地状态
      setUsers(prev => prev.map(user =>
        user.id === userId ? { ...user, isActive: !user.isActive } : user
      ))

      // TODO: 调用API更新数据库
      alert('用户状态已更新（演示模式）')
    } catch (err) {
      console.error('更新用户状态错误:', err)
      setError('更新用户状态时发生错误')
    }
  }

  const deleteUser = async (userId: string) => {
    if (!confirm('确定要删除这个用户吗？此操作不可恢复。')) {
      return
    }

    try {
      // 从本地状态删除
      setUsers(prev => prev.filter(user => user.id !== userId))

      // TODO: 调用API从数据库删除
      alert('用户已删除（演示模式）')
    } catch (err) {
      console.error('删除用户错误:', err)
      setError('删除用户时发生错误')
    }
  }

  const getRoleLabel = (role: string) => {
    return role === 'admin' ? '管理员' : '学生'
  }

  const getRoleColor = (role: string) => {
    return role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'
  }

  const getGradeLabel = (grade: number) => {
    if (grade === 0) return '管理员'
    if (grade <= 6) return `小学${grade}年级`
    return `初中${grade - 6}年级`
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  }

  const formatDateTime = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN')
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载用户列表中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8"
        >
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            用户管理
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            管理系统用户，查看用户信息和学习数据
          </p>
        </motion.div>

        {/* 操作栏 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="mb-6"
        >
          <Card glassmorphism className="backdrop-blur-xl">
            <CardContent className="p-6">
              <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
                <div className="flex flex-col sm:flex-row gap-4 flex-1">
                  {/* 搜索框 */}
                  <div className="relative flex-1 max-w-md">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Input
                      placeholder="搜索用户名、邮箱或学校..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="pl-10"
                      glassmorphism
                    />
                  </div>

                  {/* 角色筛选 */}
                  <select
                    value={selectedRole}
                    onChange={(e) => setSelectedRole(e.target.value)}
                    className="px-4 py-2 rounded-lg bg-white/20 backdrop-blur-sm border border-white/30 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">全部角色</option>
                    <option value="student">学生</option>
                    <option value="admin">管理员</option>
                  </select>

                  {/* 年级筛选 */}
                  <select
                    value={selectedGrade}
                    onChange={(e) => setSelectedGrade(e.target.value)}
                    className="px-4 py-2 rounded-lg bg-white/20 backdrop-blur-sm border border-white/30 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">全部年级</option>
                    <option value="1">小学1年级</option>
                    <option value="2">小学2年级</option>
                    <option value="3">小学3年级</option>
                    <option value="4">小学4年级</option>
                    <option value="5">小学5年级</option>
                    <option value="6">小学6年级</option>
                    <option value="7">初中1年级</option>
                    <option value="8">初中2年级</option>
                    <option value="9">初中3年级</option>
                  </select>
                </div>

                {/* 添加用户按钮 */}
                <Button
                  variant="glassmorphism"
                  className="glassmorphism-button"
                  onClick={() => {
                    // TODO: 打开添加用户对话框
                    alert('添加用户功能开发中...')
                  }}
                >
                  <UserPlus className="w-4 h-4 mr-2" />
                  添加用户
                </Button>
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {/* 错误提示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 rounded-lg bg-red-100 border border-red-300 text-red-700"
          >
            {error}
          </motion.div>
        )}

        {/* 用户列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="grid gap-6"
        >
          {filteredUsers.length === 0 ? (
            <Card glassmorphism className="backdrop-blur-xl">
              <CardContent className="p-12 text-center">
                <Users className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                <h3 className="text-xl font-semibold text-gray-600 mb-2">暂无用户</h3>
                <p className="text-gray-500">
                  {searchQuery || selectedRole || selectedGrade 
                    ? '没有找到符合条件的用户' 
                    : '系统中还没有用户'
                  }
                </p>
              </CardContent>
            </Card>
          ) : (
            filteredUsers.map((user, index) => (
              <motion.div
                key={user.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1 * index }}
              >
                <Card glassmorphism className={`backdrop-blur-xl hover:shadow-lg transition-all duration-300 ${
                  !user.isActive ? 'opacity-60' : ''
                }`}>
                  <CardHeader>
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${getRoleColor(user.role)}`}>
                            {getRoleLabel(user.role)}
                          </span>
                          <span className="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                            {getGradeLabel(user.grade)}
                          </span>
                          {!user.isActive && (
                            <span className="px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                              已禁用
                            </span>
                          )}
                        </div>
                        <CardTitle className="text-lg text-gray-800 dark:text-gray-200">
                          {user.username}
                        </CardTitle>
                        <CardDescription>
                          {user.email} • {user.school}
                        </CardDescription>
                      </div>
                      <div className="flex gap-2 ml-4">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => toggleUserStatus(user.id)}
                        >
                          <Shield className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            // TODO: 编辑用户
                            alert('编辑用户功能开发中...')
                          }}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => deleteUser(user.id)}
                          disabled={user.role === 'admin'}
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <div>
                        <p className="text-sm text-gray-600">注册时间</p>
                        <p className="font-medium">{formatDate(user.createdAt)}</p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">最后登录</p>
                        <p className="font-medium">{formatDateTime(user.lastLogin)}</p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">练习次数</p>
                        <p className="font-medium">{user.totalSessions}</p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">平均正确率</p>
                        <p className="font-medium text-blue-600">
                          {user.averageAccuracy > 0 ? `${user.averageAccuracy.toFixed(1)}%` : '-'}
                        </p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            ))
          )}
        </motion.div>

        {/* 统计信息 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="mt-8"
        >
          <Card glassmorphism className="backdrop-blur-xl">
            <CardContent className="p-6">
              <div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-300">
                <span>
                  显示 {filteredUsers.length} / {users.length} 个用户
                </span>
                <span>
                  活跃用户：{users.filter(u => u.isActive).length} 个
                </span>
              </div>
            </CardContent>
          </Card>
        </motion.div>
      </div>
    </div>
  )
}
